/*
 * str.cpp
 *
 *  Created on: 2012-9-26
 *      Author: Futbal
 */

#include "../includes/str.h"

int LengthOfStr(char* a) {
	char* p = a;
	int len = 0;
	while(*p != '\0') {
		len++;
		p++;
	}
	return len;
}

int LongestCommonSubString(char* a, char* b) {
	int max = 0;
	int lenA = LengthOfStr(a);
	int lenB = LengthOfStr(b);
	int** m = new int*[lenA];
	for(int i = 0; i < lenA; i++) {
		m[i] = new int[lenB];
	}
	for(int j = 0; j < lenB; j++) {
		if(a[0] == b[j]) {
			m[0][j] == 1;
			max = 1;
		} else {
			m[0][j] == 0;
		}
	}
	for(int i = 0; i < lenA; i++) {
		if(a[i] == b[0]) {
			m[i][0] = 1;
			max = 1;
		} else {
			m[i][0] = 0;
		}
	}

	int pos = 0;
	for(int i = 1; i < lenA; i++) {
		for(int j = 1; j < lenB; j++) {
			m[i][j] = (a[i] == b[j]) ? m[i - 1][j - 1] + 1 : 0;
			if(m[i][j] > max) {
				max = m[i][j];
				pos = i;
			}
		}
	}

	for(int i = pos - max; i < pos; i++) {
		cout<<a[i];
	}
	cout<<endl;

	for(int i = 0; i < lenA; i++) {
		delete[] m[i];
	}
	delete[] m;

	return max;
}

int MoveStarToFront(char* s) {
	char* p = s;
	int num = 0, len = LengthOfStr(p), i = len;
	p += (len - 1);
	char* q = p - 1;

	while(i > 0) {
		if(*q != '*') {
			q--;
			i--;
		} else {
			num++;
			break;
		}
	}

	p = q;
	q--;
	i--;
	while(i > 0) {
		if(*q != '*') {
			char t = *p;
			*p = *q;
			*q = t;
			p--;
		}
		q--;
		i--;
		if(*q == '*') {
			num++;
		}
	}

	return num;
}

void RemoveNumbersFromString(char* s) {
	char* p = s, *q = p;
	while(*p != '\0') {
		if(*p >= '0' && *p <= '9') {
			break;
		} else {
			p++;
		}
	}
	q = p + 1;
	while(*q != '\0') {
		if(!(*q >= '0' && *q <= '9')) {
			char t = *p;
			*p = *q;
			*q = t;
			p++;
		}
		q++;
	}
	*p = '\0';
}
